//
//  BKResultOfMatchingProvinceViewController.m
//  baokaodaxue
//
//  Created by dangyangyang on 15/5/31.
//  Copyright (c) 2015年 宏图教育. All rights reserved.
//

#import "BKResultOfMatchingProvinceViewController.h"
#import "BKColleageViewController.h"
#import "BKMatchingScoreViewModel.h"
#import "BKCompareViewController.h"
#import "BKMatchingProvViewModel.h"
#import "BKMatchingProvinceViewController.h"
#import <MBProgressHUD.h>


@interface BKResultOfMatchingProvinceViewController ()<UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UITextField *searchTextFiel;

@end

@implementation BKResultOfMatchingProvinceViewController
- (IBAction)p_compare:(id)sender {
    _dataSource.isComparing = !_dataSource.isComparing;
    [_dataSource.selectedArray removeAllObjects];
    UIButton *button = (UIButton *)sender;
    if (_dataSource.isComparing) {
        [button setTitle:@"取消" forState:UIControlStateNormal];
    }else{
    
        [button setTitle:@"比较" forState:UIControlStateNormal];
    }
    
    [_tableView reloadData];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _dataSource = [[BKMatchingProvDataSource alloc] init];
        _dataSource.isComparing= NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BKMatchingProvTableViewCell class]) bundle:nil] forCellReuseIdentifier:reuse];
    
    _tableView.dataSource = _dataSource;
    _tableView.delegate = self;
    _tableView.separatorColor = [UIColor grayColor];
    _tableView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    _tableView.layer.borderWidth = 1;
    _tableView.layer.cornerRadius = 3;
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search"]];
    _searchTextFiel.leftViewMode = UITextFieldViewModeAlways;
    _searchTextFiel.backgroundColor = [UIColor whiteColor];
    imageView.backgroundColor = [UIColor colorWithRed:64/255.0 green:188/255.0 blue:232/255.0 alpha:1.0];
    CGFloat width = imageView.bounds.size.width;
    CGFloat height = imageView.bounds.size.height;
    imageView.bounds = CGRectMake(0, 0, width + 6, height + 6);
    imageView.contentMode = UIViewContentModeCenter;
    imageView.layer.cornerRadius = 3;
    _searchTextFiel.leftView = imageView;
}

- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    UITabBarController *tabBarViewController = (UITabBarController *)[[[UIApplication sharedApplication] keyWindow] rootViewController];
    [tabBarViewController.tabBar setBarTintColor:[UIColor colorWithRed:0.459 green:0.839 blue:0.863 alpha:1.000]];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL change = [defaults boolForKey:@"province_change"];
    
    if (!change)
        return;
    
    [defaults setBool:NO forKey:@"province_change"];
    NSString *proText = [defaults objectForKey:@"province_pro_text"];
    NSString *wenliText = [defaults objectForKey:@"province_wenli_text"];
    NSString *piciText = [defaults objectForKey:@"province_pici_text"];
    NSString *leixingText = [defaults objectForKey:@"province_leixing_text"];
    
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.labelText = @"正在加载";
    [self.view addSubview:hud];
    [hud show:YES];
    
    self.dataSource.dataArray = @[];
    [self.tableView reloadData];
    
    BKMatchingProvViewModel *viewModel = [[BKMatchingProvViewModel alloc] init];
    [viewModel colleageWithProv:proText wenli:wenliText pici:piciText leixing:leixingText currentPage:@"1" success:^(NSArray *dataArray) {
        [hud hide:YES];
        [hud removeFromSuperview];
        self.dataSource.dataArray = dataArray;
        [self.tableView reloadData];
        
    } failure:^(NSString *message) {
        [hud hide:YES];
        [hud removeFromSuperview];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        [alertView show];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)p_back:(id)sender {
    
    BKMatchingProvinceViewController *pro = [[BKMatchingProvinceViewController alloc] initWithNibName:NSStringFromClass([BKMatchingProvinceViewController class]) bundle:nil];
    [self.navigationController pushViewController:pro animated:YES];
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 80;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    return [UIView new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (_dataSource.isComparing) {
        
        __block BOOL isSelected = NO;
        [_dataSource.selectedArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            if ([obj[@"cid"] isEqual:_dataSource.dataArray[indexPath.row][@"cid"] ]) {
                isSelected = YES;
                [_dataSource.selectedArray removeObject:obj];
                *stop = YES;
            }
        }];
        
        if (!isSelected) {
            if ([_dataSource.selectedArray  count]==2) {
                // 超过两个不能选择
                return;
                
            }else{
                 [_dataSource.selectedArray addObject:_dataSource.dataArray[indexPath.row]];
            
            }
        }
       
        [_tableView reloadData];

        [self performSelectorOnMainThread:@selector(compare) withObject:nil waitUntilDone:YES];
        
    }else{
        NSString *cid = _dataSource.dataArray[indexPath.row][@"cid"];
        
        BKColleageViewController *colleage = [[BKColleageViewController alloc] initWithNibName:NSStringFromClass([BKColleageViewController class]) bundle:nil];
        colleage.name = _dataSource.dataArray[indexPath.row][@"name"];
        colleage.cid = cid;
        
        [self presentViewController:colleage animated:YES completion:nil];

    
    
    }
    
}


- (void)compare{
    
    if ([_dataSource.selectedArray count]!=2)
        return;
    
    [BKMatchingScoreViewModel compareCol:[NSString stringWithFormat:@"%@,%@",_dataSource.selectedArray[0][@"cid"],_dataSource.selectedArray[1][@"cid"]] success:^(NSArray *dataArray) {
        dispatch_queue_t mainQueue = dispatch_get_main_queue();
        dispatch_async(mainQueue, ^(void) {
            BKCompareViewController *compare = [[BKCompareViewController alloc] initWithNibName:NSStringFromClass([BKCompareViewController class]) bundle:nil];
            compare.dataArray = dataArray;
            [self presentViewController:compare animated:YES completion:nil];
        });
        
        
        
    } failure:^(NSString *message) {
        dispatch_queue_t mainQueue = dispatch_get_main_queue();
        dispatch_async(mainQueue, ^(void) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
            [alertView show];});
        
        
        
    }];
    
    
}
@end
